import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/entity/my/my_interact_entity.dart';
import 'package:ball_lion/entity/my/my_system_msg_entity.dart';
import 'package:ball_lion/server/api/user_api.dart';

class MySystemMsgLogic extends GetxController with GetTickerProviderStateMixin {
  List<MySystemMsgEntity> msgs = [];
  int msgPage = 1;
  bool msgEnd = false;

  List<MyInteractEntity> interacts = [];
  int interPage = 1;
  bool interEnd = false;

  int sysCount = 0;
  int interactCount = 0;
  int tabIndex = 0;

  late final tabC =
      TabController(length: 2, vsync: this, initialIndex: tabIndex);

  @override
  void onInit() {
    super.onInit();
    tabC.addListener(() {
      if (tabC.index != tabIndex) {
        tabIndex = tabC.index;
      }
    });
  }

  @override
  void onReady() {
    super.onReady();
    getMsgs();
    getInteracts();
    getUnreadCounts();
  }

  @override
  void onClose() {
    super.onClose();
    tabC.dispose();
  }

  getUnreadCounts({bool msg = true, bool inter = true}) async {
    UserApi.getSystemUnreadCount().then((value) {
      if (value != null) {
        sysCount = value;
        update();
      }
    });
    UserApi.getInterUnreadCount().then((value) {
      if (value != null) {
        interactCount = value;
        update();
      }
    });
  }

  getMsgs() async {
    final page = msgPage;
    final l = await UserApi.getSystemMsg(page: page);
    if (page != msgPage) {
      return;
    }
    if (l != null) {
      msgs.addAll(l);
      msgPage += 1;
    }
    msgEnd = (l?.length ?? 1) == 0;
    update();
  }

  getInteracts() async {
    final page = interPage;
    final l = await UserApi.getInteract(page: page);
    if (page != interPage) {
      return;
    }
    if (l != null) {
      interacts.addAll(l);
      interPage += 1;
    }
    interEnd = (l?.length ?? 1) == 0;
    update();
  }

  readMsg(MySystemMsgEntity msg) async {
    final result = await UserApi.readSystemMsg(msg.id!);
    if (result == 200) {
      msg.read = 1;
      getUnreadCounts(inter: false);
      update();
    }
  }

  readInteract(MyInteractEntity inter) async {
    final result = await UserApi.readInteract(inter.id!);
    if (result == 200) {
      inter.read = 1;
      getUnreadCounts(msg: false);
      update();
    }
  }

  String getUnreadNum(int num) {
    if (num > 99) {
      return '99+';
    } else if (num > 0 && num < 99) {
      return '$num';
    } else {
      return '';
    }
  }

  readAllMsg() {
    for (MySystemMsgEntity msg in msgs) {
      msg.read = 1;
    }
    UserApi.readSystemMsg(-1);
    sysCount = 0;
    update();
  }

  readAllInter() {
    for (MyInteractEntity element in interacts) {
      element.read = 1;
    }
    UserApi.readInteract(-1);
    interactCount = 0;
    update();
  }

  clearMsg() {
    tabIndex == 0 ? readAllMsg() : readAllInter();
  }
}
